package com.yingxin.yx.framework.commons.helper;

import com.yingxin.yx.framework.commons.exception.BizException;

import java.lang.reflect.Field;

public class ClassHelper {

    public static <T> Object getFieldVal(T t, String fieldName) {
        try {
            Class<?> clz = t.getClass();
            Field field = clz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(t);
        } catch (Exception ignored) {
        }
        // 没找到就去父类找
        try {
            Class<?> clz = t.getClass().getSuperclass();
            Field field = clz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(t);
        } catch (Exception ignored) {
        }
        throw new BizException("获取字段异常");
    }

    public static <T> void setFieldVal(T t, String fieldName, Object val) {
        try {
            Class<?> clz = t.getClass();
            Field field = clz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(t, val);
            return;
        } catch (Exception ignored) {
        }
        // 没找到就去父类找
        try {
            Class<?> clz = t.getClass().getSuperclass();
            Field field = clz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(t, val);
            return;
        } catch (Exception ignored) {
        }
        throw new BizException("获取字段异常");
    }
}